package org.tbjd.client.customWidgets;

import java.util.HashMap;
import java.util.Map;

import org.tbjd.client.constants.NotificationsConstants;
import org.tbjd.client.exceptions.TBJDException;
import org.tbjd.client.interfaces.Decisionmaker;

import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.Widget;

public class CustomGrid extends Grid implements Decisionmaker {

	private int rowClicked, columnClicked;
	Map<Integer, Integer> map = new HashMap<Integer, Integer>();

	public CustomGrid() {
		super();
	}

	public CustomGrid(int rows, int columns) {
		super(rows, columns);
		sinkEvents(Event.ONDBLCLICK);
	}

	public void onBrowserEvent(Event event) {
		super.onBrowserEvent(event);
		decide(event);
	}

	public void decide(Object action) {
		if (action instanceof Event && DOM.eventGetType((Event) action) == Event.ONDBLCLICK) {
			Element td = getEventTargetCell((Event) action);
			if (td == null) {
				return;
			}
			Element tr = DOM.getParent(td);
			Element body = DOM.getParent(tr);
			rowClicked = DOM.getChildIndex(body, tr);
			columnClicked = DOM.getChildIndex(tr, td);

			this.map = new HashMap<Integer, Integer>();
			this.map.put(NotificationsConstants.OPEN_PROJECT, rowClicked);

			delegate(this.map);
		} else {
			delegate(action);
		}
	}

	public void delegate(Object action) {
		// passes info to the upper decisionmaker
		Widget parent = ((Widget) this).getParent();
		while (parent != null && parent instanceof Decisionmaker == false) {
			parent = ((Widget) parent).getParent();
		}
		if (parent != null) {
			try {
				((Decisionmaker) parent).decide(action);
			} catch (TBJDException e) {
				e.printStackTrace();
			}
		} else {
			System.out.println("no parent or responsible founded !");
		}
	}

	public void handle(Object action) {
	}

	public int getRowClicked() {
		return rowClicked;
	}

	public int getColumnClicked() {
		return columnClicked;
	}

}
